package com.example.rabbitmqp;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Author：wlz
 * @Package：com.example.rabbitmqc
 * @Project：redis
 * @name：Producer
 * @Date：2023/4/10 21:30
 * @Filename：Producer
 */
public class Producer_PubSub {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1.创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        //2.设置参数
        factory.setHost("127.0.0.1");
        factory.setPort(5672);
        factory.setVirtualHost("/");
        factory.setUsername("guest");
        factory.setPassword("guest");
        //3.获取连接Connection
        Connection connection = factory.newConnection();
        //4.创建Channel
        Channel channel = connection.createChannel();

        // 创建交换机
        //参数
        /*
        1.参数 exchange：交换机名称
        2.type：交换机类型
        3.durable：是否持久化
        4.outDelete：是否持久化
        5.internal：内部使用，一般false
        6.arguments：参数

         */
        String exchangeName = "test_";

        channel.exchangeDeclare(exchangeName, BuiltinExchangeType.FANOUT,true,false,false,null);

        //5.创建队列
        /*
        queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments)
        1.队列名称
        2.durable是否持久化，当mq重启之后还在
         */
        String queueName1 = "test_1";
        String queueName2 = "test_2";

        channel.queueDeclare(queueName1,true,false,false,null);
        channel.queueDeclare(queueName2,true,false,false,null);


        //绑定交换机和队列

        /*
        1.queue：队列名称
        2.exchange：交换机名称
        3.routingKey：路由键，绑定规则，如果交换机的类型为fanout，默认为空

         */

        channel.queueBind(queueName1,exchangeName,"");
        channel.queueBind(queueName2,exchangeName,"");

        //6.发送消息
        /*
        basicPublish(String exchange, String routingKey, BasicProperties props, byte[] body)

         */

        String body = "rizhi-------";

        channel.basicPublish(exchangeName,"",null,body.getBytes());

        //7.释放资源
        channel.close();
        connection.close();

    }
}
